import { ICleanService } from './../common/dataClean/cleanManager';
import { DeliveryOrder } from './../domain/model';
import { DataContextFactory } from './../domain/fbsDataContext';
import { ServiceException } from "./serviceException";
import { Guid, Logger, ObjectCopier, intersectionArray, uniqueArray, differenceArray } from "../common/utils";
import { Transaction } from "tiny-entity";
import { DateFormat } from "./../common/utils";
import assert = require("assert");
import * as _ from "lodash";
import * as R from "ramda";
import * as moment from "moment";

export class DeliveryOrderService implements ICleanService {

    get ServiceName() {
        return "deliveryOrderService";
    }

    async CleanData() {
        let ctx = DataContextFactory.GetDataContext();
        const time = moment().startOf('day').subtract(1, 'days').valueOf();
        const result = await ctx.DeliveryOrder.ToList();
        const orders = result.filter(x => x.beginTime < time);
        for (let data of orders) {
            await this.ctx.Delete(data);
        }
    }

    private get ctx() {
        return DataContextFactory.GetDataContext();
    }

    constructor() {
    }


    async deliveryOrder(ids: Array<string>, deliverer: {
        id: string,
        name: string
    },
        serialNo: string,
        terminalId: string
    ) {
        // 生成传菜单
        let deliveryOrder = new DeliveryOrder();
        deliveryOrder.beginTime = new Date().getTime();
        deliveryOrder.finishTime = new Date().getTime();
        deliveryOrder.expediteOrderIds = ids;
        deliveryOrder.id = Guid.GetGuid();
        deliveryOrder.status = 'delivered';
        deliveryOrder.terminalId = terminalId;
        deliveryOrder.serialNo = serialNo;
        deliveryOrder.deliveryerId = deliverer.id;
        deliveryOrder.deliveryer = deliverer;

        deliveryOrder = await this.ctx.Create(deliveryOrder);
        return deliveryOrder;
    }

    async GetDeliveryOrders(query: {
        start: Number
    }) {
        let orders = this.ctx.DeliveryOrder;
        if(query.start) {
            orders.Where(
                x => x.beginTime >= query.start,
                ['query.start'],
                [query.start]
            );
        }
        let deliveryOrders: Array<DeliveryOrder> = await orders.ToList();
        return deliveryOrders;
    }
}